package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Version: V1.0
 */
@Slf4j
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior>
        implements ApFollowBehaviorService {

    /**
     * 存储关注数据
     *
     * @param dto
     * @return
     */
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {
        //1 参数检查
        if (dto == null || dto.getArticleId() == null
                || dto.getFollowId() == null || dto.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //1.查询行为实体
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getUserId(), null);
        if (behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存关注行为
        ApFollowBehavior alb = getOne(Wrappers.<ApFollowBehavior>lambdaQuery()
                .eq(ApFollowBehavior::getEntryId,behaviorEntry.getId())
                .eq(ApFollowBehavior::getFollowId, dto.getFollowId()));

        if (alb == null) {

            alb = new ApFollowBehavior();
            alb.setEntryId(behaviorEntry.getId());  // 行为实体主键
            alb.setCreatedTime(new Date());
            alb.setArticleId(dto.getArticleId());
            alb.setFollowId(dto.getFollowId());
            save(alb);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
